//
//  STReadStoryViewController.swift
//  Story
//
//  Created by 汤泽川 on 2019/4/23.
//  Copyright © 2019 汤泽川. All rights reserved.
//

import Foundation
import UIKit
import RxSwift
import RxCocoa
import GTMRefresh
import Alamofire
import PKHUD

class STReadStoryViewController: UIViewController, STStoryCommentViewDelegate {
    
    private let storyInfo : STStoryInfo
    
    init(model : STStoryInfo) {
        self.storyInfo = model
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        buildView()
    }
    
    private func buildView() {
        let commentVM = STStoryCommentViewModel(commentId: nil, storyId: self.storyInfo.storyInfo.id, authorId: self.storyInfo.authorInfo.id)
        let commentView = STStoryCommentView(viewModel: commentVM)
        commentVM.loadMore()
        commentView.delegate = self
        self.view.addSubview(commentView)
        commentView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        SessionManager.default.request(self.storyInfo.storyInfo.storyUrl).responseString { (response) in
            switch response.result {
            case .success( _) :
                commentView.setupStoryHeader(model: self.storyInfo, content: String(data: response.data!, encoding: .utf8)!)
            case .failure( _) :
                HUD.flash(.labeledError(title: nil, subtitle: "获取小说失败，请稍后再试"))
            }
        }
        
    }
    
    func didClickComment(model: STCommentInfo) {
        let commentVC = STCommentViewController(commentModel: model)
        commentVC.delegate = self
        commentVC.title = String(model.replayCount) + "条回复"
        self.present(commentVC, animated: true, completion: nil)
    }
    func didClickUserAvatar(authorName: String) {
        let storyManager = STSearchAuthorListServiceManager(pageCount: 20)
        storyManager.authorName = authorName
        let collectVC = STUserStoryFeedViewController(storyManager: storyManager)
        collectVC.title = "\(authorName)写的的故事"
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(collectVC, animated: true)
    }
    
}
